package xyz.yolin.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import xyz.yolin.pojo.*;
import xyz.yolin.service.QuestionService;
import xyz.yolin.service.SurveyService;
import xyz.yolin.utils.MapControl;
import xyz.yolin.utils.SessionUtils;
import xyz.yolin.utils.SystemInit;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.*;

@Controller
@RequestMapping("/survey")
public class SurveyController {
    @Autowired
    private SurveyService surveyService;
    @Autowired
    private QuestionService questionService;

    @RequestMapping("add")
    public String toCreate(){
        return "survey/add";
    }

    @RequestMapping("/create")
    @ResponseBody
    public Map<String,Object> create(@RequestBody Survey survey, HttpServletRequest request) {
        System.out.println("前端获取到的数据"+survey);
        Admin curradmin = SessionUtils.getAdmin(request);
        System.out.println(curradmin);
        survey.setCreator(curradmin.getId());
        System.out.println("问卷状态："+Survey.state_create);
        survey.setState(Survey.state_create);
        survey.setAnon(survey.getAnon()!=null?0:1);
        int result=surveyService.create(survey);
        if (result<=0){
            return MapControl.getInstance().err().getMap();
        }
        return MapControl.getInstance().success().getMap();
    }

    @ResponseBody
    @PostMapping("/delete")
    public Map<String,Object> delete(String str){
        System.out.println(str);
        int result = surveyService.delete(str);
        if (result<=0){
            return MapControl.getInstance().err().getMap();
        }
        return MapControl.getInstance().success().getMap();
    }

    @RequestMapping("/update")
    @ResponseBody
    public Map<String,Object> update(@RequestBody Survey survey){
        System.out.println("前端发送来的survey"+survey);
        survey.setAnon(survey.getAnon()!=null?0:1);
        int result = surveyService.update(survey);
        if (result<=0){
            return MapControl.getInstance().err().getMap();
        }
        return MapControl.getInstance().success().getMap();
    }
    @PostMapping("/query")
    @ResponseBody
    public Map<String, Object> query(@RequestBody Survey survey){
        //设置分页，参数1表示从第几页开始，参数2表示一页多少条记录
        PageHelper.startPage(survey.getPage(),10);

        if (LoginController.currUser!=1){
            survey.setCreator(LoginController.currUser);
        }

        //查到所有问卷
        List<Survey> list = surveyService.query(survey);

        for(Survey survey1:list){
            //survey.getCreator()就是id号
            survey1.setAdmin(SystemInit.adminMap.get(survey1.getCreator()));
            System.out.println("创建者："+survey1.getCreator());
//            if (survey1.getCreator().equals(currId)){
//                System.out.println(11111111);
//            }
        }
        System.out.println(list.size());
        System.out.println("list:"+list);
        Integer count=surveyService.count(survey);
        return MapControl.getInstance().page(list,count).getMap();
    }

    @RequestMapping("/detail")
    public String detail(Integer id, ModelMap modelMap){
        Survey survey= surveyService.detail(id);
        modelMap.addAttribute("survey",survey);
        return "survey/update";
    }

    @GetMapping("/list")
    public String list(){
        return "survey/list";
    }

    @GetMapping("/echart")
    public String echart(){
        return "survey/echart";
    }

    @GetMapping("/question")
    public String question(Integer id,ModelMap modelmap){
        Survey survey = surveyService.detail(id);
        modelmap.addAttribute("survey",survey);
        return "survey/question";
    }

    @GetMapping("/preview/{id}")
    public String preview(@PathVariable("id") Integer id,ModelMap modelMap){
        Survey survey = surveyService.detail(id);
        Question question = new Question();
        question.setSurveyId(survey.getId());
        //查询一个问卷中的所有问题及选项
        List<Question> questions = questionService.query(question);
        //将问题设置为survey的属性
        survey.setQuestions(questions);
        modelMap.addAttribute("survey",survey);
        return "survey/preview";
    }
    @GetMapping("/preview_echart/{id}")
    public String preview_echart(@PathVariable("id") Integer id,ModelMap modelMap) throws JsonProcessingException {
        //根据id查询出对应的问卷
        Survey survey = surveyService.detail(id);
        Question question = new Question();
        question.setSurveyId(survey.getId());
        //查询一个问卷中的所有问题及选项
        List<Question> questions = questionService.query(question);
        //将问题设置为survey的属性
        survey.setQuestions(questions);


        //总投票人数
        AnswerOpt answerOpt = new AnswerOpt();
        answerOpt.setSurveyId(id);
        List<AnswerOpt> answerOpts = surveyService.queryAnswerOpt(answerOpt);
        Set<String> set=new HashSet<String>();
        for (AnswerOpt opt:answerOpts){
            set.add(opt.getJoiner());
        }
        //所有选项
        List<String> list = new ArrayList<>();
        List<Integer> Valuelist = new ArrayList<>();

        ObjectMapper mapper= new ObjectMapper();
        //遍历所有问题，及选项

        List<Echart> myech=new ArrayList<>();
        for (Question question1:questions){
            System.out.println("----"+question1);
            for (QuestionOpt questionOpt:question1.getOptions()){
                //+++++QuestionOpt(id=1, surveyId=1, questionId=1, opt=爬山, orderby=1, answer=null, type=2, num=null)
                System.out.println("+++++"+questionOpt);
                list.add(questionOpt.getOpt());
                HashMap<String,String> map=new HashMap<>();
                map.put("name",questionOpt.getOpt());

                String s=mapper.writeValueAsString(questionOpt.getOpt());
                System.out.println("SSSSSSSSSS"+s);
                int num=0;
                for (AnswerOpt opt:answerOpts){
                    if (questionOpt.getId()==opt.getOptId()){
                        num++;
                    }
                }
                myech.add(new Echart(num,questionOpt.getOpt()));

                questionOpt.setNum(num);
                Valuelist.add(num);
            }

        }


        System.out.println("XXXXXXXXXXXXXX"+list);
        modelMap.addAttribute("str",list);
        System.out.println(answerOpts);
        System.out.println(Valuelist);


        modelMap.addAttribute("Valuelist",Valuelist);
        modelMap.addAttribute("survey",survey);
        String myech1 = mapper.writeValueAsString(myech);
        System.out.println("myech--->"+myech1);
        modelMap.addAttribute("myech",myech1);
        System.out.println(survey);
        System.out.println(set);
        modelMap.addAttribute("total",set.size());
        return "survey/preview_echart";
    }
    @PostMapping("/publish")
    @ResponseBody
    public Map<String,Object> publish(Integer id,HttpServletRequest request){

        System.out.println("发布问卷获取到的id:"+id);
        Survey param = surveyService.detail(id);
        System.out.println("param:"+param);
        if(!Survey.state_exec.equals(param.getState())){
            return MapControl.getInstance().err("操作失败，当前问卷未在执行中！").getMap();
        }
        String uuid = "/dy/"+UUID.randomUUID().toString();
        Survey survey = new Survey();
        survey.setId(id);
        //http://localhost:8080/survey/ieieas-asdf-asdf-3-asd-f-asdf
        String url = "http://"+request.getServerName()+ ":" + request.getServerPort() + request.getContextPath()+uuid;
        System.out.println("拼接后的链接地址："+url);
        survey.setUrl(url);
        surveyService.update(survey);
        return MapControl.getInstance().success().getMap();
    }

    @PostMapping("/submit")
    @ResponseBody
    public Map<String,Object> submit(@RequestBody List<Map<String,Object>> list){

        List<AnswerOpt> optList = new ArrayList();
        List<AnswerTxt> txtList = new ArrayList();

        String uuid = UUID.randomUUID().toString();
        for (Map<String, Object> stringObjectMap : list) {
            if(object2String(stringObjectMap.get("type")).equals("1") || object2String(stringObjectMap.get("type")).equals("2")){
                List<Object> opts = (List<Object>) stringObjectMap.get("opts");
                for (Object opt : opts) {
                    AnswerOpt answerOpt = new AnswerOpt();
                    answerOpt.setQuestionId(object2Integer(stringObjectMap.get("questionId")));
                    answerOpt.setSurveyId(object2Integer(stringObjectMap.get("surveyId")));
                    answerOpt.setType(object2String(stringObjectMap.get("type")));
                    answerOpt.setOptId(object2Integer(opt));
                    answerOpt.setCreateTime(new Date());
                    answerOpt.setJoiner(uuid);
                    optList.add(answerOpt);
                }
            }
            if(object2String(stringObjectMap.get("type")).equals("3") || object2String(stringObjectMap.get("type")).equals("4")){
                AnswerTxt answerTxt = new AnswerTxt();
                answerTxt.setQuestionId(object2Integer(stringObjectMap.get("questionId")));
                answerTxt.setSurveyId(object2Integer(stringObjectMap.get("surveyId")));
                answerTxt.setResult(object2String(stringObjectMap.get("result")));
                answerTxt.setCreateTime(new Date());
                answerTxt.setVoter(uuid);
                txtList.add(answerTxt);
            }
        }
        surveyService.submit(optList,txtList);
        return MapControl.getInstance().success().getMap();
    }
    public String object2String(Object object){
        if(object !=null){
            return object+"";
        }else{
            return null;
        }
    }
    public Integer object2Integer(Object object){
        if(object !=null){
            return Integer.parseInt(object+"");
        }else{
            return null;
        }
    }

    //修改密码
//    @RequestMapping("/toUpdatePwd")
//    public String toUpdatePwd(){
//        return "user-password";
//    }
}
